/***
 * Maram Lee 20180910
 * 表头固定，原生js
 * ***/
 !(function (z) {
    if(!z.ml) z.ml={};
    let getOffset=function (obj) {
        let top=obj.offsetTop;
        let left=obj.offsetLeft;
        while(obj.offsetParent){
            let style,borderTop,borderLeft;
            obj=obj.offsetParent;
            style=getComputedStyle(obj);
            borderTop=parseInt(style.borderTopWidth);
            borderLeft=parseInt(style.borderLeftWidth);
            top+=obj.offsetTop;
            left+=obj.offsetLeft;
            if(borderTop) top+=borderTop;
            if(borderLeft) left+=borderLeft;
        }
        return {top,left};
    };
    let Fix=function (x,e){
        this.e=e;
        this.bgColor=x.bgColor||"#fff";
    };
    Fix.prototype.init=function(){
        let that=this;
        let e=this.e;
        let trChild=e.firstElementChild.firstElementChild.children;
        let newHead=e.firstElementChild.cloneNode(true);
        let table=document.createElement("table");
        table.className=e.className;
        table.style.position="fixed";
        table.style.top=getOffset(e).top+"px";
        table.style.left=getOffset(e).left+"px";
        table.style.backgroundColor=this.bgColor;
        this.setCellsWidth(trChild,newHead,table);
        table.appendChild(newHead);
        e.parentNode.appendChild(table);
        this.onresize(function () {
            that.setCellsWidth(trChild,newHead,table)
        });
    };
    Fix.prototype.setCellsWidth=function(trChild,newHead,table){
        let allWidth=1;
        for(let i=0;i<trChild.length;i++){
            let w=trChild[i].clientWidth+1;
            allWidth+=w;
            newHead.children[0].children[i].width=w;
        }
        table.style.width=allWidth+"px";
    };
    Fix.prototype.onresize=function (fn){
        let originFn = window.onresize;
        window.onresize =function (){
            originFn && originFn();
            fn();
        }
    };
    z.ml.fixTableHead=function(x){
        let ele=document.querySelectorAll(x.el);
        ele.forEach((e)=>{
            let n=new Fix(x,e);
            n.init();
        });
    };
})(window);